//
//  HomeViewController.swift
//  01sinablog
//
//  Created by ZhangZiang on 15/12/12.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

private let HomeCellID = "HomeCell"

class HomeViewController: BaseTableViewController {

    lazy var timelineList : [Timeline] = [Timeline]()
    
    private lazy var refreshView : WBRefreshControl = WBRefreshControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if UserAccountViewModel().isUserLogin == false
        {
        visitorView?.setupVisitorInfo("登录后，别人评论你的微博，发给你的消息，都会在这里收到通知", imageName: nil)
        }
        else
        { 
            setupUI()
            
            loadData()
        }
        
    }
    
    //一到主界面就下拉刷新一次
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        loadData()
    }
    
    private func setupUI()
    {
        //注册要重用的cell类
        tableView.registerClass(TimelineCell.self, forCellReuseIdentifier: HomeCellID)
        
        //先用300
        //            tableView.rowHeight = 300
        //必须给cell的contentview设置了约束,预估高度才能生效
        tableView.estimatedRowHeight = 300
        
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.separatorStyle = .None
        
        //来一个菊花指示器(最上面的下拉刷新)
//        refreshControl = UIRefreshControl()
        tableView.addSubview(refreshView)
        //给指示器加方法
        refreshView.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        
        tableView.tableFooterView = indicator
        
//        tableView.addSubview(tipLabel)
        self.navigationController?.navigationBar.addSubview(tipLabel)
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //获取当前登录用户及其所关注（授权）用户的最新微博
   @objc private func loadData() {
        
    var since_id : Int64 = 0
    var max_id : Int64 = 0
    
        //如果最下面的菊花在转动,则说明是加载更多,否则是下拉刷新
        if indicator.isAnimating()
        {
            since_id = 0
            max_id = timelineList.last?.id ?? 0
        }
        else
        {
            max_id = 0
            since_id = timelineList.first?.id ?? 0
            
        }
        
        TimelineViewModel.loadHomeViewData(since_id, max_id: max_id) { (timelineList) -> () in
            self.refreshView.endRefresh()
            guard let list = timelineList else
            {
                return
            }
            
//            self.timelineList = list
            
            if since_id > 0
            {
                //下拉刷新
                self.timelineList = list + self.timelineList//list是新的微博
//                self.refreshControl?.endRefreshing()
               
                //显示刷到了多少条
                self.showTipLabelAnimation(list)
            }
            else if max_id > 0
            {
                //上拉加载更多
                self.timelineList = self.timelineList + list
                self.indicator.stopAnimating()
            }
            else
            {
                //首次
                self.timelineList = list
            }
            
            self.tableView.reloadData()
        }
        
  
        }
    
    private func showTipLabelAnimation(list : [Timeline]) {
        tipLabel.text = "有\(list.count)条新微博"
        
        var rect = tipLabel.frame
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            rect.size.height = 44
            
            self.tipLabel.frame = rect
            }) { (_) -> Void in
                //延迟2s后执行收回动画
                UIView.animateWithDuration(0.5, delay: 2, options: [], animations: { () -> Void in
                    rect.size.height = 0
                    
                    self.tipLabel.frame = rect
                    }, completion: { (_) -> Void in
                        
                })
        }
    }
    
    //MARK: 懒加载控件
    //懒加载一个菊花指示器(位于最下面footerView)
   private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    //懒加载刷新提示label
    private lazy var tipLabel : UILabel = {
        let tl = UILabel(title: "", color: UIColor.blackColor(), fontSize: 18)
        tl.backgroundColor = themeColor
        
        tl.frame = CGRect(x: 0, y: 44, width: ScreenW, height: 0)
        
        return tl
    }()
}

extension HomeViewController {
    // MARK : tableView的代理和数据源方法
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return timelineList.count ?? 0
    }
  
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> TimelineCell
    {
       
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! TimelineCell
        
        cell.timeline = timelineList[indexPath.row]
//        cell.textLabel?.text = (timelineList[indexPath.row].user?.name) ?? "0"
        //如果要到最后一条&&指示器没转,就开始加载更多的数据
        if indexPath.row == timelineList.count - 1 && !indicator.isAnimating()
        {
            indicator.startAnimating()
            loadData()
        }

        //默认是灰色,改成None就没有点击变色了
        cell.selectionStyle = .None
        
        return cell
    }
}

